import { Component, OnInit, Input, Injector } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import { debounceTime } from 'rxjs/operators/debounceTime';
import { map } from 'rxjs/operators/map';
import { switchMap } from 'rxjs/operators/switchMap';
import { ActivatedRoute, NavigationExtras } from '@angular/router';
import { NzMessageService, NzModalService, NzModalRef, UploadFile } from 'ng-zorro-antd';
import { importExpr } from '@angular/compiler/src/output/output_ast';
import { environment } from 'environments/environment';

import {
  PagedResultDto, ClassInfoOutput, PagerSearchInput, HttpService, BaseComponentConfig,
  CustomNavigation, KeyValueOutput, SearchValue
} from '../..';
import { NgZorroPageBaseComponent } from '../../core/ng-zorro-page-base-component/ng-zorro-page-base-component.component';
import { StudentJoinCourseOutput } from '../../core/model/StudentJoinCourseDto';
import { isNumber } from 'util';
import { ExpressionPair, Compare, AndOr } from '../../core/model/CommonDto';
import { AuthService } from '../../core/service/auth.service';

@Component({
  selector: 'app-mytrain',
  templateUrl: './mytrain.component.html',
  styleUrls: ['./mytrain.component.scss']
})
export class MytrainComponent extends NgZorroPageBaseComponent implements OnInit {
  listUrl = 'ClassInfo/GetClassByName';
  searchChange$ = new BehaviorSubject(new SearchValue('', ''));
  optionList = [];
  selectedUser;
  // 选择上传的主题
  selectRecordId;
  // 开始演练
  startDrillId;
  confirmModal: NzModalRef;
  /**
   * 是否从远程获取数据
   */
  isLoading = false;
  //  上传
  uploading = false;
  _fileList: UploadFile[] = [];
  get fileList() {
    return this._fileList;
  }
  set fileList(value) {
    this._fileList = value;
    if (this._fileList.length > 0) {

    }
  }
  get finishCount() {
    return this.listEntities.entities.filter(e => e.drillStatus === 2).length;
  }

  _searchType = 0;
  get searchType(): number {
    return this._searchType;
  }
  set searchType(v: number) {
    if (this._searchType === v) {
      this._searchType = 0;
    } else {
      this._searchType = v;
    }
    this.listSearchValue = new Array<ExpressionPair>(
      new ExpressionPair('status', this._searchType.toString(), Compare.Equal, AndOr.And),
    );
    this.getEntityList();
  }
  get roleType() {
    return this.authService.token.userRoleType;
  }

  //
  onSearch(value: string, url: string): void {
    this.isLoading = true;
    this.searchChange$.next(new SearchValue(value, this.listUrl));
  }

  ngOnInit() {
    this.listEntities.pageSize = 12;
    this.IniObserver.subscribe(sb => {
      this.getEntityList();
    });
  }

  constructor(
    injecter: Injector,
    public authService: AuthService,
    private modal: NzModalService,
    private modalService: NzModalService,
    public http: HttpService) {
    super(injecter,
      new BaseComponentConfig(
        "DrillRecord/GetPagerDrillRecord",
        "",
        "",
        "",
        "",
        "id",
        "",
        "",
        [],
        "",
        { Edit: false, Dell: false },
      ));

  }
  // 开始演练
  async startDrill(id, drillType, driistatus) {
    this.startDrillId = id;
    if (driistatus !== 0) {
      const startpar = { Id: this.startDrillId };
      const result = await this.httpService.post<any>('DrillRecord/StartDrillRecord', startpar);
      const navigationExtras: NavigationExtras = {
        queryParams: { 'id': id }
      };
      if (drillType === 0) {
        this.router.navigate(['/mydrillcontent'], navigationExtras);
      } else if (drillType === 1) {
        this.router.navigate(['/drag-train'], navigationExtras);
      } else if (drillType === 2) {
        this.router.navigate(['/videoteaching'], navigationExtras);
      }

    } else {
      this.confirmModal = this.modal.confirm({
        nzTitle: '是否要开始演练?',
        nzContent: '点击确定后，此演练的信息将不能更改。',
        nzOnOk: async () => {

          const startpar = { Id: this.startDrillId };
          const result = await this.httpService.post<any>('DrillRecord/StartDrillRecord', startpar);
          const navigationExtras: NavigationExtras = {
            queryParams: { 'id': id }
          };
          if (drillType === 0) {
            this.router.navigate(['/mydrillcontent'], navigationExtras);
          } else if (drillType === 1) {
            this.router.navigate(['/drag-train'], navigationExtras);
          } else if (drillType === 2) {
            this.router.navigate(['/videoteaching'], navigationExtras);
          }
          // this.router.navigate(['/mydrillcontent'], navigationExtras);
          // location.reload();
        },
        nzOnCancel: () => {

        }
      });
    }

  }
  // 跳转到演练步骤
  async toDrillStep(value: any) {
    const navigationExtras: NavigationExtras = {
      queryParams: { 'id': value.id }
    };
    this.router.navigate(['/mydrillcontent'], navigationExtras);
  }

  beforeUpload = (file: UploadFile): boolean => {
    this.fileList.push(file);
    this.confirmModal = this.modal.confirm({
      nzTitle: `确认`,
      nzContent: `是否要上传演练报告${file.name}?`,
      nzOnOk: async () => {
        await this.handleUpload();
        this.message.success('上传成功!');
        this.getEntityList();
      },
      nzOnCancel: () => {

      }
    });
    return false;
  }
  async selectDrill(subjectId: number) {
    this.selectRecordId = subjectId;
  }
  async handleUpload() {
    const formData = new FormData();
    // tslint:disable-next-line:no-any
    formData.append('drillRecordId', this.selectRecordId);
    this.fileList.forEach((file: any) => {
      formData.append('fileinput', file);
    });
    this.uploading = true;
    // You can use any AJAX library you like
    // const startpar = { Id: this.startDrillId };
    const req = await this.http.post<any>('DrillRecord/UploadReport', formData);
  }

  // 删除演练
  async deleteDrill(id) {
    this.confirmModal = this.modal.confirm({
      nzTitle: '是否要删除演练?',
      nzContent: '点击确定后，此演练的信息将被删除。',
      nzOnOk: async () => {
        await this.httpService.get<any>('DrillRecord/DeleteDrillRecord?id=' + id);
        this.getEntityList();
      },
      nzOnCancel: () => {

      }
    });
  }
  getIndex(index: number) {
    index += 1;
    let reslut = index > 4 ? index % 4 : index;
    reslut = reslut === 0 ? reslut + 1 : reslut;
    return reslut;
  }
}
